//
//  RSSReaderViewController.m
//  vnex
//
//  Created by sieg on 8/26/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "RSSReaderViewController.h"
#import "RSSItemViewCell.h"

@implementation RSSReaderViewController

@synthesize tblView;
@synthesize selectRSSItemTitle;
@synthesize selectRSSItemURL;
@synthesize rssItems;

#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {	
    [super viewDidLoad];
	
	[self loadRSS:selectRSSItemURL];
	
	self.navigationItem.title = selectRSSItemTitle;	
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [self.tblView performSelectorOnMainThread:@selector(reloadData) 
								   withObject:nil 
								waitUntilDone:NO];
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [rssItems count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kTableViewRowHeight;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {    
    static NSString *CellIdentifier = @"RSSCell";
    
    RSSItemViewCell *cell = (RSSItemViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	
    if (cell == nil) {
        cell = [[[RSSItemViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
		NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"RSSCell" owner:nil options:nil];
		
		for(id currentObject in topLevelObjects)
		{
			if([currentObject isKindOfClass:[RSSItemViewCell class]])
			{
				cell = (RSSItemViewCell *)currentObject;
				break;
			}
		}
    }
    
    // Configure the cell...
	NSArray *rssArray = [rssItems objectAtIndex:indexPath.row];
	
	cell.cellTitle.text = [rssArray objectAtIndex:0];
	cell.cellContent.text = [self getDescription:[rssArray objectAtIndex:1]];
	NSURL *url = [NSURL URLWithString:[self getImageFromDescription:[rssArray objectAtIndex:1]]];
	NSData *data = [NSData dataWithContentsOfURL:url];
	UIImage *img = [[UIImage alloc] initWithData:data];
    cell.cellImage.image = img;
		
    return cell;
}


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
    /*
    <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
    // ...
    // Pass the selected object to the new view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
    */
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    //selectRSSItemTitle = nil;
	//selectRSSItemURL = nil;
}

- (void)loadRSS:(NSString *)url {
	
	NSLog(@"%@",url);
	TBXML *xmlParser = [[TBXML tbxmlWithURL:[NSURL URLWithString:url]] retain];
	
	rssItems = [NSMutableArray array];
	[rssItems retain];
	
	if (xmlParser.rootXMLElement) {
		[self traverseElement:xmlParser.rootXMLElement];
	}
	[xmlParser release];
	
}

- (void)traverseElement:(TBXMLElement *)element {
	
	do {
		if (element->firstChild) {
			[self traverseElement:element->firstChild];
		}
		
		if ([[TBXML elementName:element] isEqualToString:@"item"]) {
			TBXMLElement *itemTitle = [TBXML childElementNamed:@"title" parentElement:element];
			TBXMLElement *itemDescr = [TBXML childElementNamed:@"description" parentElement:element];
			TBXMLElement *itemLink = [TBXML childElementNamed:@"link" parentElement:element];
			
			[rssItems addObject:[NSArray arrayWithObjects:
								 [TBXML textForElement:itemTitle],
								 [TBXML textForElement:itemDescr],
								 [TBXML textForElement:itemLink],nil]];
		}
	} while (element = element->nextSibling);
	
}

- (NSString*)getDescription:(NSString *)description{
    NSString *string;
    NSScanner *scanString =[NSScanner scannerWithString:description];
	
    while ([scanString isAtEnd] == NO) {
        [scanString scanUpToString:@"<" intoString:NULL];
        [scanString scanUpToString:@">" intoString:&string];
        
		description = [description stringByReplacingOccurrencesOfString:
					   [NSString stringWithFormat:@"%@>",string] withString:@""];
    }
	
    return description;
}

- (NSString *)getImageFromDescription:(NSString *)description {
    NSArray *tempArray = [description componentsSeparatedByString:@"src"];
	
    if ([tempArray count] > 1) {		
		NSString *tempString = [tempArray objectAtIndex:1];
		NSArray *tempArray2 = [tempString componentsSeparatedByString:@"\""];
		NSString *tempString2 = [tempArray2 objectAtIndex:1];
		return tempString2;
    }
	else{
        return nil;
    }
}

- (void)dealloc {
	[selectRSSItemTitle release];
	[selectRSSItemURL release];
	[rssItems release];
	[tblView release];
    [super dealloc];
}

@end

